package com.pxst.sys.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.pxst.sys.req.IsUseReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.pxst.entity.LoginUser;
import com.pxst.resp.ApiResp;
import com.pxst.sys.entity.AuthorityEntity;
import com.pxst.sys.mapper.AuthorityMapper;
import com.pxst.sys.service.AuthorityService;
import com.pxst.utils.SecurityFrameworkUtils;

/** 
* @author yangxy
* @version 创建时间：2023年7月27日 下午4:03:53 
*/
@Service
public class AuthorityServiceImpl extends ServiceImpl<AuthorityMapper, AuthorityEntity> implements AuthorityService {
	@Autowired
	private AuthorityMapper authorityMapper;
	
	@Override
	@SuppressWarnings("unchecked")
	public ApiResp<AuthorityEntity> getAuthority() {
		// TODO Auto-generated method stub
		LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
		List<AuthorityEntity> authList = Lists.newArrayList();
		if(loginUser.getIsAdmin() == 0) {//超级管理员用户所有权限
			authList.addAll(list(new QueryWrapper<AuthorityEntity>().lambda().eq(AuthorityEntity::getIsUse, 0)));
		}else {
			authList.addAll(authorityMapper.getHaveAuthByUserId(SecurityFrameworkUtils.getLoginUserId()));
		}
		//取出权限中的功能权限仅保留菜单和按钮权限
		List<AuthorityEntity> menuList = authList.stream().filter(vo->vo.getAuthorityType() != 3).collect(Collectors.toList());
		//筛选出顶级权限列表
		List<AuthorityEntity> topAuthList = menuList.stream().filter(vo->ObjectUtils.isEmpty(vo.getPid())).collect(Collectors.toList());
		topAuthList.forEach(vo->{
			this.authTree(vo, menuList);
		});
		
		return ApiResp.sucess(topAuthList);
	}

	@Override
	public ApiResp<String> addAuthority(AuthorityEntity authority) {
		String authorityCode = authority.getAuthorityCode();
		// 对输入的权限编码进行格式校验，必须是xxx.xxx格式
		if(!authorityCodeValidator(authorityCode))
			return ApiResp.paramError("权限编码格式不符合规则，请按照 xxx.xxx 的格式传入");
		// 判断权限编码是否已存在
		QueryWrapper<AuthorityEntity> wrapper = new QueryWrapper<>();
		wrapper.eq("authority_code",authorityCode);
		AuthorityEntity auth = authorityMapper.selectOne(wrapper);
		if(auth == null)
			return ApiResp.sucess(authorityMapper.insert(authority));
		return ApiResp.paramError("权限编码已存在");
	}

	@Override
	public ApiResp<List<AuthorityEntity>> getAllAuthority(Integer mode) {
		List<AuthorityEntity> resList = new ArrayList<>();
		QueryWrapper<AuthorityEntity> wrapper = new QueryWrapper<>();
		if(mode == 1 || mode == 0){
			wrapper.eq("is_use",mode);
		}
		List<AuthorityEntity> authList = authorityMapper.selectList(wrapper);
		for (AuthorityEntity authority : authList) {
			AuthorityEntity topAuth = this.authTree(authority,authList);
			resList.add(topAuth);
		}
		return ApiResp.sucess(resList);
	}

	@Override
	public ApiResp<String> changeIsUse(IsUseReq isUseReq) {
		if (!isUseReq.getDisableList().isEmpty())
			authorityMapper.changeIsUse(isUseReq.getDisableList(),0);
		if (!isUseReq.getEnableList().isEmpty())
			authorityMapper.changeIsUse(isUseReq.getEnableList(),1);
		return ApiResp.sucess("OK");
	}

	@Override
	public ApiResp updateAuthority(AuthorityEntity authority) {
		if(!authorityCodeValidator(authority.getAuthorityCode()))
			return ApiResp.paramError("权限编码格式不符合规则，请按照 xxx.xxx 的格式传入");
		AuthorityEntity auth = authorityMapper.selectOne(
				new QueryWrapper<AuthorityEntity>().eq("authority_code",authority.getAuthorityCode())
		);
		if(auth == null || Objects.equals(auth.getAuthorityCode(), authority.getAuthorityCode()))
			return ApiResp.sucess(authorityMapper.updateById(authority));
		return ApiResp.paramError("权限编码已存在");
	}

	@Override
	public ApiResp<String> deleteAuthority(Long id) {
		QueryWrapper<AuthorityEntity> wrapper = new QueryWrapper<>();
		AuthorityEntity authority = authorityMapper.selectById(id);
		if(authority == null)
			return ApiResp.paramError("传入的权限id不存在");
		authorityMapper.deleteById(id);
		return ApiResp.sucess("删除成功!");
	}

	/**
	 * @Author: @Ryan
	 * @Description: 判断权限编码是否符合规则
	 * @Date: 2023/9/8 10:37
	 * @Param: [code-权限编码]
	 * @return: java.lang.Boolean
	 **/
	public Boolean authorityCodeValidator(String code){
		if(!code.matches("[a-zA-Z0-9]+[.][a-zA-Z0-9]+")){
			System.out.println("参数错误: 权限编码格式不符合规则，请遵循 xxx.xxx 的格式传入" );
			return false;
		}
		return true;
	}


	/**
	 * 组装权限列表为树形结构(递归方式)
	* @author yangxy
	* @version 创建时间：2023年7月27日 下午4:42:24 
	* @return
	 */
	private AuthorityEntity authTree(AuthorityEntity topAuth,List<AuthorityEntity> allList){
		List<AuthorityEntity> children = Lists.newArrayList();
		for (AuthorityEntity vo : allList) {
			if (topAuth.getId().longValue() == vo.getId().longValue()) {
				continue;
			} 
			if (!ObjectUtils.isEmpty(vo.getPid()) && vo.getPid().longValue() == topAuth.getId().longValue()) {
				this.authTree(vo, allList);
				children.add(vo);
			}
		}
		topAuth.setChildren(children);
		return topAuth;
	}



}
